package com.practice;


import java.util.HashSet;
import java.util.Set;

public class Solution {
    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
    //1.哈希：
    public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
        Set<ListNode> set = new HashSet<ListNode>();
        ListNode temp = headA;
        while (temp != null) {
            set.add(temp);
            temp = temp.next;
        }
        temp = headB;
        while (temp != null) {
            if (set.contains(temp)) {
                return temp;
            }
            temp = temp.next;
        }
        return null;
    }
    //双指针
    public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        if(headA == null && headB != null) {
            return null;
        }
        if(headA != null && headB == null) {
            return null;
        }
        ListNode plong = headA;
        ListNode pshort = headB;
        int len1 = 0;
        int len2 = 0;
        while (plong != null) {
            len1++;
            plong = plong.next;
        }
        while (pshort != null) {
            len2++;
            pshort = pshort.next;
        }
        plong = headA;
        pshort = headB;
        int len = len1 - len2;
        if (len < 0) {
            plong = headB;
            pshort = headA;
            len = len2 - len1;
        }
        while (len != 0) {
            plong = plong.next;
            len--;
        }
        while (plong != pshort) {
            plong = plong.next;
            pshort = pshort.next;
        }
        return pshort;
    }
}